<?php

namespace App\Lib\_Error;

use App\Lib\_Application\Resources\ApiResource;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

/**
 * Class NotDataException
 * @package App\Lib\_Error;
 */
class LibBaseException extends \Exception
{
    const DEFAULT_CODE = 205;
    protected $code = self::DEFAULT_CODE;

    /**
     * 自定义错误处理
     * @param Request $request
     * @param \Exception $exception
     * @return \Illuminate\Http\JsonResponse|mixed
     */
    public static function exceptionHandle(Request $request, \Exception $exception): ?JsonResponse
    {
        // 数据库回滚
        if ($exception instanceof TransactionException) {
            DB::rollBack();
        }
        // 调用模型的findOrFail 和 firstOrFail方法未找到异常
        if ($exception instanceof ModelNotFoundException) {
            $resource = new ApiResource($exception, NotDataException::DEFAULT_MESSAGE, self::DEFAULT_CODE);
            return $resource->toResponse($request);
        }
        if ($exception instanceof \Exception) {
            $resource = new ApiResource($exception);
            return $resource->toResponse($request);
        }
        return null;
    }
}